package com.lits.search.hotKeys;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.lits.search.hotKeys.func.IFrequencyHotkeys;

public class MemoryFrequencyHotkeys implements IFrequencyHotkeys {
	private static final int MAX_KEYS = 500;
	private Map<String, Integer> nowKeys;
	private Map<String, Integer> previousKeys;
	private Map<String, Integer> queryCache;
	
	private long startRecordTime;
	
	/**
	 * 统计周期：时间毫秒数
	 */
	private long cntCyc = HOUR;

	/**
	 * 设置定期汇总周期
	 * @param cyc
	 */
	public void setCntCyc(long cyc) {
		this.cntCyc = cyc;
	}
	/**
	 * 去除无用词，如：空格，tab，','，'"'，'''，'|'，"+"，"!"，"$"等
	 * @param key
	 * @return
	 */
	public String transferKey(String key) {
		return key.replaceAll(PATTERN_DOT, "");
	}

	/**
	 * 去除语义词
	 * @param key
	 * @return
	 */
	public boolean isSemantics(String key) {
		return key.matches(SEMANTICS_STR);
	}

	public int createKeyRepository() {
		if(nowKeys != null){
			return 1;
		}
		synchronized(this){
			if(nowKeys == null) {
				nowKeys = new ConcurrentHashMap<String, Integer>();
			}
		}
		return 1;
	}

	/**
	 * 超出最大key存储数量或者超出统计周期，会清空缓存库，保存当前内容到数据库
	 */
	public int addKey(String key) {
		if (!validateKey(key)) {
			return -1;
		}
		key = transferKey(key);
		if (!validateKey(key)) {
			return -1;
		}
		if(isSemantics(key)) {
			return -2;
		}
		if(nowKeys.containsKey(key)){
			nowKeys.put(key, nowKeys.get(key) + 1);
		} else {
			nowKeys.put(key, 1);
		}
		long nowTime = new Date().getTime();
		
		if(startRecordTime == 0) {
			startRecordTime = nowTime;
		}
		long spent = nowTime - startRecordTime;
		if(nowKeys.size() == MAX_KEYS  || spent > this.cntCyc) {
			startRecordTime = nowTime;
			previousKeys =  new ConcurrentHashMap<String, Integer>();
			previousKeys.putAll(nowKeys);
			nowKeys = new ConcurrentHashMap<String, Integer>();
			new Thread(new Runnable(){
				public void run() {
					storeKeyRepository(previousKeys);
					
				}}){
				
			}.start();
		}
		
		return 1;
	}

	public boolean validateKey(String key) {
		if(key == null || key.length() == 0){
			return false;
		}
		return true;
	}

	public int storeKeyRepository(Map<String, Integer> keys) {
		
		return 0;
	}

	public List<String> getTopHot(int rangeInt) {
		
		return null;
	}
	
	public static void main(String[] args) {
		//System.out.println(new MemoryFrequencyHotkeys().transferKey("\"aaa$ff"));
	}

}
